package net.helix.core.loader;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;

import net.helix.core.Face;
import net.helix.core.UV;
import net.helix.core.Vertex;
import net.helix.core.geometry.Geometry_Material;
import net.helix.core.geometry.Geometry_Mesh;
import net.helix.element.Element_Mesh;
import net.helix.engine.Engine;
import net.helix.engine.library.items.LibraryItem_Mesh;
import net.helix.engine.library.items.LibraryItem_Model;
import net.helix.ui.panels.library.LibraryTreeTableModel;
import com.longlinkislong.games.Model3DS;

public class Model3DSLoader extends ModelLoader{
	
	public Model3DSLoader(Engine engine, LibraryTreeTableModel treeModel, String addr) {
		super(engine, treeModel, addr);
		
		System.out.println("Load 3ds "+addr);
		
		Model3DS model = null;
		
		try {
			model = new Model3DS(new FileInputStream(file));
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		
		Geometry_Material material = new Geometry_Material();
		
		System.out.println("num of vertices "+model.vertices.length);
		
		for(int i=0;i<model.vertices.length;i++){
			vertices.add(new Vertex(model.vertices[i].x, model.vertices[i].y, model.vertices[i].z));
		}
		
		for(int i=0;i<model.mapcoords.length;i++){
			uvs.add(new UV(model.mapcoords[i].x, model.mapcoords[i].y));
		}
		
		
		// TODO: support multiple meshes?
		ArrayList<Face> faces = new ArrayList<Face>();
		for(int i=0;i<model.polygons.length;i++){
			faces.add(new Face(model.polygons[i].x, model.polygons[i].y, model.polygons[i].z, model.polygons[i].x, model.polygons[i].y, model.polygons[i].z, -1, -1, -1));
		}
		
		
	
		Geometry_Mesh mesh = new Geometry_Mesh();
		mesh.setFaces(faces);
		
		mesh.setShadingSmooth(this, material);
		
		
		
		if(treeModel != null){
			LibraryItem_Model newModel = new LibraryItem_Model(treeModel.getLibrary(), file.getName());
			
			ArrayList<Element_Mesh> meshElements = new ArrayList<Element_Mesh>();
			
			
				LibraryItem_Mesh newMesh = new LibraryItem_Mesh(treeModel.getLibrary(), "mesh "+1);
				
				newMesh.setMaterial(material);
				newMesh.setMesh(mesh);
				
				newMesh.setModel(this);
				
				
				treeModel.addNewItem(newMesh);
				
				
				Element_Mesh newMeshElement = new Element_Mesh(newMesh);
				
				meshElements.add(newMeshElement);
			
			
			newModel.setMeshes(meshElements);
			
			treeModel.addNewItem(newModel);
			
		}
		
		
	}
	
}
